#include "AsyncConnector.h"

U2L::AsyncConnector::AsyncConnector(void)
{
	m_connecting = false;
	m_done = false;
	m_socket = NULL;
}

U2L::AsyncConnector::~AsyncConnector(void)
{
	this->Wait();
}

void U2L::AsyncConnector::Connect(sf::SocketTCP* _socket, unsigned short _port, sf::IPAddress _ip, float _timeout)
{
	if (_socket != NULL &&
		_ip.IsValid() &&
		!m_connecting)
	{
		m_socket = _socket;
		m_port = _port;
		m_ip = _ip;
		m_timeout = _timeout;
		m_connecting = true;
		m_done = false;
		this->Launch();
	}
}

bool U2L::AsyncConnector::IsConnecting(void) const
{
	return m_connecting;
}

bool U2L::AsyncConnector::IsDone(void) const
{
	return m_done;
}

void U2L::AsyncConnector::Run(void)
{
	try
	{
		if (m_socket->Connect(m_port, m_ip, m_timeout) == sf::Socket::Done)
		{
			m_done = true;
		}
		m_socket = NULL;
		m_connecting = false;
	}
	catch (std::exception& err)
	{
		std::cerr << err.what() << std::endl;
	}
}